﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using CarsRegistrationService.Models;
using System.Web.Configuration;
using System.Security.Cryptography;
using System.Text;

namespace CarsRegistrationService.Managers
{
    public abstract class BaseLinqManager
    {
        private CarsRegistrationDBEntities linqContext;
        protected CarsRegistrationDBEntities LinqContext
        {
            get
            {
                if (this.linqContext == null)
                {
                    var connectionString = WebConfigurationManager.
                        ConnectionStrings["CarsRegistrationDBEntities"].ConnectionString;
                    this.linqContext = new CarsRegistrationDBEntities(connectionString);
                }
                return this.linqContext;
            }
        }

        private MD5 md5;

        public BaseLinqManager()
        {
            this.md5 = MD5.Create();
        }

        protected string MD5Encode(string input)
        {
            byte[] dataInput = Encoding.Default.GetBytes(input);
            byte[] data = this.md5.ComputeHash(dataInput);
            StringBuilder sBuilder = new StringBuilder();

            for (int i = 0; i < data.Length; i++)
            {
                sBuilder.Append(data[i].ToString("x2"));
            }

            return sBuilder.ToString();
        }


        protected bool MD5Verify(string input, string hash)
        {
            string hashOfInput = this.MD5Encode(input);
            StringComparer comparer = StringComparer.OrdinalIgnoreCase;
            return comparer.Compare(hashOfInput, hash) == 0;
        }

    }
}